package org.example.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.ReferenceCountUtil;

public class ByteBufDemo {
    public static void main(String[] args) {
        ByteBuf buffer = Unpooled.buffer();
        printBuf(buffer);

        // 写入字节
        printMsg("\n写入4个字节");
        buffer.writeBytes(new byte[]{1,2,3,4});
        printBuf(buffer);

        // read字节不改变readerIndex
        printMsg("\nget方法读一个字节，不改变readerIndex的值：" + buffer.getByte(0));
        printBuf(buffer);

        printMsg("\nread方法读一个字节，readerIndex递增：" + buffer.readByte());
        printBuf(buffer);

        // 内存释放
        printMsg("\n缓冲区释放");
        // 等同buffer.release();
        ReferenceCountUtil.release(buffer);
        printBuf(buffer);

        try {
            printMsg("" + buffer.getByte(0));
        } catch (Exception ex) {
            printMsg("内存释放之后再次读取数据，报错：" + ex.getMessage());
        }

        // 测试一下
        ByteBuf buf = Unpooled.buffer(9, 100);
        buf.writeInt(10);
        buf.writeInt(20);
        buf.writeInt(30);
        printBuf(buf);
    }

    public static void printBuf(ByteBuf buf) {
        System.out.println("buffer:" + buf);
        System.out.println("writerIndex:" + buf.writerIndex());
        System.out.println("readerIndex:" + buf.readerIndex());
        System.out.println("writeableBytes:" + buf.writableBytes());
        System.out.println("readableBytes:" + buf.readableBytes());
        System.out.println("capacity:" + buf.capacity());
        System.out.println("maxCapacity:" + buf.maxCapacity());
        System.out.println("引用次数:" + buf.refCnt());
    }

    public static void printMsg(String msg) {
        System.out.println(msg);
    }
}
